// pages/square/public1.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "发布", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    publicContent: "",
    typeList: [{
      id: 0,
      name: '图片'
    }, {
      id: 1,
      name: '视频'
    }],
    classId: 0,
    taskList: [{
      id: 0,
      name: '话题1'
    }, {
      id: 1,
      name: '话题2'
    }],
    taskId: 0,
    uploadType: '图片',
    task: '请选择一个话题',
    images: [], //上传图片集合
    videoSources: [{
        url: '',
        type: 'video',
        poster: ''
      }, //上传视频地址
    ],
    videoFmt: '',
    isHeightModeArr: [],
    videoMax: 100, //上传视频的大小限制M
    imgMax: 10, //上传图片的大小限制M

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,
    showPrivacy: false,

    openid: '',
    shareImg: '',
    shareTitle: '',
    is_nickAndHead: 0,
    targetList: [],

    sendImgArr: [], //提交数据时的图片
    sendVideoArr: [], //提交数据时的视频
    videoMax: 0, //上传视频的大小限制M
    imgMax: 0, //上传图片的大小限制M
  },
  bindTextAreaBlur: function(e) {
    let value = e.detail.value.replace(/\n/g, '<br/>');
    this.setData({
      publicContent: value
    })
  },
  //选择上传类型
  typeChange(e) {
    let that = this;
    that.setData({
      uploadType: that.data.typeList[e.detail.value].name,
      classId: e.detail.value
    })
  },
  //选择话题
  taskChange(e) {
    let that = this;
    that.setData({
      task: that.data.taskList[e.detail.value].target,
      taskId: that.data.taskList[e.detail.value].id
    })
  },


  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const {
      width,
      height,
    } = e.detail
    let index = e.currentTarget.dataset.index;
    console.log("height:" + height + ".....width" + width + "....e:" + e)
    let isHeightModeArr = this.data.isHeightModeArr;
    if (height >= width) {
      isHeightModeArr[index] = true;
      this.setData({
        isHeightModeArr
      })
    }

  },
  //删除图片
  delFile(e) {
    let that = this;
    let delNum = e.currentTarget.dataset.index;
    let images = that.data.images;
    let isHeightModeArr = that.data.isHeightModeArr;
    images.splice(delNum, 1);
    isHeightModeArr.splice(delNum, 1);
    that.setData({
      images: images,
      isHeightModeArr: isHeightModeArr
    })
  },
  // 预览图片
  previewImage(e) {
    let that = this,
      imgsrc = e.currentTarget.dataset.presrc,
      arr = that.data.images
    //console.log(preArr)
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },

  previewVideo(e) {
    let {
      sources
    } = e.currentTarget.dataset
    console.log("sources:", sources)
    var url = sources[0].url
    wx.previewMedia({
      sources,
      current: 0,
      url: url
    })
  },
  delVideo() {
    let that = this;
    let videoSources = that.data.videoSources;
    videoSources[0].url = "";
    that.setData({
      videoSources: videoSources
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = 154;

        //算出当前宽度下高度的数值
        width = proportion * windowWidth;
        that.setData({
          height: windowWidth,
          width
        });
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }


    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getPublic1PageInfo(res.data.openid);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getPublic1PageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },


  getPublic1PageInfo(openid) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getPublic1PageInfo.php',
      method: 'POST',
      data: {
        openid: openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({

            taskList: res.data.targetList,
            is_nickAndHead: res.data.is_nickAndHead,
            videoMax: res.data.videoMax,
            imgMax: res.data.imgMax
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },

  //关闭指引
  closeZy() {
    this.setData({
      showPrivacy: false,
      showLogin: false,
      showWsInfoDom: false
    });
  },

  //点击查看协议指引
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  },

  //点击同意协议
  handleAgreePrivacyAuthorization() {
    this.setData({
      showPrivacy: false,
      showPrivacyFlag: true
    });
    app.globalData.showPrivacyFlag = true;
  },

  /**
   * 上传视频
   */
  chooseVideo: function() {
    let that = this;

    //判断是否同意了引导协议
    if (app.globalData.showPrivacyFlag == false) {
      that.setData({
        showPrivacy: true
      })
      return;
    }

    wx.chooseMedia({
      count: 1,
      sourceType: ['album', 'camera'],
      mediaType: ['video'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        if (res.tempFiles[0].size / 1024 / 1024 > parseInt(that.data.videoMax)) {
          app.showTip('视频不能大于' + parseInt(that.data.videoMax) + 'M哦');
          return;
        }

        let videoSources = that.data.videoSources;
        videoSources[0].url = res.tempFiles[0].tempFilePath

        // res.tempFiles[0].thumbTempFilePath  这个是封面图
        that.setData({
          videoSources: videoSources,
          videoFmt: res.tempFiles[0].thumbTempFilePath
        })
        console.log(res);
        console.log(videoSources)
      },
      fail: function(res) {

        console.log(res)
      }
    });
  },

  //上传图片
  upLoadImg: function(e) {
    let that = this;

    //判断是否同意了引导协议
    if (app.globalData.showPrivacyFlag == false) {
      that.setData({
        showPrivacy: true
      })
      return;
    }

    wx.chooseImage({
      count: 10 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        let images = that.data.images;
        let isHeightModeArr = that.data.isHeightModeArr;
        if ((images.length + tempFilePaths.length) > 9) {
          app.showTip("最多只能上传9张");
          return;

        }
        for (var item in res.tempFilePaths) {
          that.data.images.push(res.tempFilePaths[item]);
          isHeightModeArr.push(false);
          tempFilePaths = that.data.images;
        }
        //限制上传图片大小为5M,所有图片少于5M才能上传
        let size = res.tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (size) {
          that.setData({
            images: tempFilePaths,
            isHeightModeArr: isHeightModeArr
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");

        }
      }
    })
  },

  //提交最终数据
  public() {
    let that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    let publicContent = that.data.publicContent;
    let target = that.data.task;
    let tid = that.data.taskId;
    //let choosedTalkList = that.data.choosedTalkList;
    if (publicContent == "") {
      app.showTip("请输入您想说的内容");
      return;
    }
    if (target == '' || target == '请选择一个话题') {
      app.showTip("请选择话题");
      return;
    }

    //调用上传
    if (that.data.classId == 0) {
      //上传图片
      //判断是否有附件
      if (that.data.images.length == 0) {
        //没有附件
        that.sub(0);
      } else {
        //有附件上传附件
        that.sendFj(1);
      }
    } else {
      //上传视频
      if (that.data.videoFmt.length == '') {
        //没有附件
        that.sub(0);
      } else {
        //有附件上传附件
        that.sendFj(2);
      }
    }
  },

  //提交最终数据
  sub(fjType) {
    //提交数据
    var that = this;
    wx.showLoading({
      title: '信息发布中...'
    });

    wx.request({
      url: that.data.baseUrl + 'addForum.php',
      method: 'POST',
      data: {
        'fjType': fjType,
        'openid': that.data.openid,
        'content': that.data.publicContent,
        'tid': that.data.taskId,
        //'choosedTalkList': JSON.stringify(that.data.choosedTalkList),
        'imgArr': JSON.stringify(that.data.sendImgArr),
        'videoArr': JSON.stringify(that.data.sendVideoArr)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip(res.data['msg']);
          setTimeout(function() {
            wx.switchTab({
              url: '/pages/square/index'
            });
          }, 1500);
        } else {
          app.showTip(res.data['msg']);
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //将附件保存至服务器
  sendFj(fjType) {
    var that = this;
   

    if (fjType == 1) {
      //上传了图片
      that.uploadImgHandle(0);
    } else {
    wx.showLoading({
      title: '信息发布中...'
    });
      //上传视频
      for (var j = 0; j < 2; j++) {
        var is_fmt = j == 0 ? 1 : 0;
        var fileInfo = '';


        if (j == 0) {
          fileInfo = that.data.videoFmt;
        } else {
          fileInfo = that.data.videoSources[0].url
        }
        wx.uploadFile({
          url: that.data.baseUrl + "uploadsForum.php", //服务器接口
          method: 'POST',
          filePath: fileInfo,
          header: {
            'content-type': 'multipart/form-data'
          },
          name: 'file', //服务器定义的Key值
          formData: {
            'fjType': 2,
            'is_fmt': is_fmt
          },
          success: function(res) {
            //wx.hideLoading();
            console.log(res.data);
            if (res.data) {
              var sendVideoArr = that.data.sendVideoArr;
              sendVideoArr.push(res.data);
              that.setData({
                sendVideoArr: sendVideoArr
              });

              if (that.data.sendVideoArr.length == 2) {
                //调用最终上传数据
                wx.hideLoading();
                that.sub(2);
              }
            } else {
              app.showTip('服务器保存视频失败,请刷新页面重试');
            }
          },
          fail: function() {
            wx.hideLoading();
            app.showTip('服务器繁忙,请稍候重试');
          }
        });
      }
    }
  },


  //处理图片上传
  uploadImgHandle(row){
     
     var that=this;
     wx.showLoading({
      title: '信息发布中...'
    });
         wx.uploadFile({
          url: that.data.baseUrl + "uploadsForum.php", //服务器接口
          method: 'POST',
          filePath: that.data.images[row],
          header: {
            'content-type': 'multipart/form-data'
          },
          name: 'file', //服务器定义的Key值
          formData: {
            'fjType': 1
          },
          success: function(res) {
            //wx.hideLoading();
            console.log(res.data);
            if (res.data) {
              var sendImgArr = that.data.sendImgArr;
              sendImgArr.push(res.data);
              that.setData({
                sendImgArr: sendImgArr
              });

              if (that.data.images.length == that.data.sendImgArr.length) {
                //调用最终上传数据
                wx.hideLoading();
              
                that.sub(1);
              }else{
                that.uploadImgHandle(row+1);
              }
            } else {
              app.showTip('服务器保存图片失败,请刷新页面重试');
            }
          },
          fail: function() {
            wx.hideLoading();
            app.showTip('服务器繁忙,请稍候重试');
          }
        });
  },


  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  //接收子组件电话授权及头像昵称授权后后返回的值
  returnVal(e) {
    var that = this;
    //授权完头像昵称
    this.setData({
      is_nickAndHead: 1
    });

    app.showTip('个人信息已完善');
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})